1. /* timer.cpp by K.Tsuru */
  2. /**************************************************************
  3. Timer class
  4. reference:H.Hisano,C Magazine No.9(1993 Soft Bank,in Japanese)
  5. ***************************************************************/
  6. #include "timer.h"
  7. double Timer::unitSecond = -1.0;
  8. int Timer::timerObjects = 0;
  9. double Timer::lossTime[maxTimer];
  10. // constructor
  11. Timer::Timer(bool start):usesClock(true){ //Stand by in default.
  12. objectID = timerObjects; //It begins at 0.
  13. timerObjects++;
  14. if(unitSecond <= 0){
  15. int i;
  16. for(i=0; i<maxTimer;i++) lossTime[i] =0.0;
  17. GetUnitSecond();
  18. }
  19. active = start;
  20. if(active) Start();
  21. }
  22. //destructor
  23. Timer::~Timer(){
  24. lossTime[objectID] = 0.0;
  25. timerObjects--;
  26. }
  27. void Timer::GetUnitSecond(){
  28. unsigned n = 0;
  29. clock_t s = clock();
  30. clock_t e;
  31. while(clock() == s); /*wait next boundary*/
  32. e = clock();
  33. while(clock() == e) ++n; //wait within one step
  34. s = clock();
  35. unitSecond = (double(s - e)/CLOCKS_PER_SEC)/(double)n;
  36. }
  37. double Timer::WaitTick(double *lt){
  38. unsigned n = 0;
  39. double sec;
  40. clock_t s = clock(); //present value
  41. while(clock() == s) ++n; //wait next value
  42. s = clock(); //value after one step
  43. sec = (double)s/(double)CLOCKS_PER_SEC;//passed time since start of program
  44. //loss time in this routine
  45. *lt = (double)n*unitSecond;
  46. return sec;
  47. }
  48. double Timer::StopWatch(timer sw){
  49. double lt;
  50. int j;
  51. if(!active || (objectID >= maxTimer)) return 0;
  52. if(sw == START) {
  53. /*wait next tick and let it the starting time*/
  54. startClock = WaitTick(&lt);
  55. for(j = 0; j < objectID; j++) lossTime[j] += lt;
  56. startTime = time(NULL);
  57. return 0.0;
  58. }
  59. // sw == STOP || LAP && active = true
  60. double t, dt;
  61. time_t now = time(NULL);
  62. dt = difftime(now, startTime);
  63. if(dt > 1000.0){
  64. usesClock=false;
  65. return dt;
  66. }
  67. /*wait next tick and let it the ending time*/
  68. double stop = WaitTick(&lt);
  69. for(j = 0; j < timerObjects; j++) lossTime[j] += lt;
  70. t = stop - startClock - lossTime[objectID];
  71. //It is possible t<0 by error. Order of -1.0e-5.
  72. if(t < 0.0) t = 0.0;
  73. return t;
  74. }

timer.cpp : last modifiled at 2017/04/06 15:01:06(2,141 bytes)
created at 2016/04/11 11:17:21
The creation time of this html file is 2017/10/07 10:54:16 (Sat Oct 07 10:54:16 2017).